import React, {useEffect, useState} from 'react'
import {Form, Button, Input, Modal, Row, Col, DatePicker, Descriptions, Select, Image, Upload, message } from 'antd'
import {connect} from 'umi'
import {genderList, isAuditList, auditStatusList, registeredStatusList} from '@/utils/constant'
import moment from 'moment'
import {getUploadUrl} from '@/utils/upload'
import {UploadOutlined} from '@ant-design/icons';

const FormItem = Form.Item;
const {Option} = Select;

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};
const formLayout = {
  labelCol: {span: 7},
};

const CreateForm = (props) => {
  const {onSubmit, onCancel, loading, visible, operateType, record} = props;
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([])
  const [fileName, setFileName] = useState(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState(null);


  useEffect(() => {
    if (visible) {
      if (record) {
        form.setFieldsValue({
          ...record, birthday: moment(record.birthday).format('YYYY-MM-DD'),
          startTime: moment(record.startTime), endTime: moment(record.endTime), urls: record.fileUrl
        })
        let fileUrlList = record.fileUrl ? record.fileUrl.split(',') : []
        setFileList(fileUrlList.map((item, index) => {
          return {
            uid: index,
            url: item,
          }
        }))
      }
    } else {
      form.resetFields()
      setFileList([])
    }
  }, [visible]);

  const fileProps = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange (res) {
      const { status } = res.file
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`)
        } else {
          setFileList(res.fileList.map(
            (item) => {
              if (item.response) {
                return {
                  uid: item.uid,
                  name: item.name,
                  status: item.status,
                  url: item.response,
                }
              } else {
                return item
              }
            }
          ))
          message.success(`${res.file.name} 文件上传成功`)
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`)
      }
    },
    onRemove (info) {
      let urls = [...fileList]
      let index = urls.findIndex(item => item.uid === info.uid)
      if (index > -1) {
        urls.splice(index, 1)
      }
      setFileList(urls)
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    setFileList([]);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    let id = record.id;
    let status = operateType === 0 ? 2 : 1;
    onSubmit({...fieldsValue, status, id,  fileUrl: fileList?.map(item => item.url).toString()});
  };

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewVisible(true);
    setPreviewImage(file.url || file.preview);
  };

  const handleChange = () =>{
    setPreviewVisible(false);
    setPreviewImage(null);
  };

  const footer = () => <><div style={{textAlign:'center'}}><Button onClick={() => handleChange()}>关闭</Button></div></>;

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="姓名">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="idcard" label="身份证">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="gender" label="性别">
              <Select disabled={true}>
                {genderList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="birthday" label="出生年月">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialNo" label="证书编号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="startTime" label="授予时间">
              <DatePicker className='widthStyle' disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialLevel" label="证书级别">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobSeries" label="职称系列">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="credentialName" label="资格名称">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="profession" label="专业">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="approvalAuthority" label="批准机关">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="hangStatus" label="是否挂证">
              <Select disabled={true}>
                {registeredStatusList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="status" label="资质审批状态">
              <Select disabled={true}>
                {auditStatusList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="endTime" label="到期时间" rules={[{required: true,message: '到期时间不能为空！'}]}>
              <DatePicker className='widthStyle' disabled={operateType!==1}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="mangerNo" label="管理编号" rules={[{required: true,message: '管理编号不能为空！'}]}>
              <Input disabled={operateType!==1}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="registerOrg" label="注册单位" rules={[{required: true,message: '注册单位不能为空！'}]}>
              <Input disabled={operateType!==1}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="isAudit" label="是否年审" rules={[{required: true,message: '请选择是否年审！'}]}>
              <Select disabled={operateType!==1}>
                {isAuditList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="fileUrl" label="证件照片" rules={[{ required: true, message: '证件照片不能为空' }]}>
              <Upload {...fileProps} disabled={operateType!==1} accept='.jpg,.png,.jpeg,.BMP' listType="picture-card" onPreview={handlePreview}>
                {fileList?.length >= 10 || operateType!==1 ? null : <><UploadOutlined/> 上传照片</>}
              </Upload>
            </FormItem>
            <Modal maskClosable={false} centered bodyStyle={{ padding: '20px' }} footer={footer()}
                   visible={previewVisible} closable={false} onCancel={handleChange}>
              <img alt="example" style={{ width: '100%' }} src={previewImage}/>
            </Modal>
          </Col>
        </Row>

      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>{operateType !== 2 ?'取消':'关闭'}</Button>
        {
          operateType !== 2 &&
          <Button type="primary" onClick={() => handleSubmit()} loading={loading}>确定</Button>
        }
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      title='资质管理'
      width='75%'
      visible={visible}
      bodyStyle={{padding: '0 5%'}}
      footer={renderFooter()}
      onCancel={() => onFormCancel()}
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(CreateForm)
